import UserService from '../../api/user';

Page({
  data: {
    userInfo: {}
  },

  onLoad() {
    // 读取本地缓存的用户信息
    const userInfo = wx.getStorageSync('userInfo') || {};
    this.setData({ userInfo });
  },
  // 表单输入时更新 userInfo 中对应字段
  onInput(e) {
    const key = e.currentTarget.dataset.key;
    this.setData({
      [`userInfo.${key}`]: e.detail.value
    });
  },
  click1() {
    wx.navigateBack({
      delta: 1  // 返回上一级页面
    });
  } ,
  updateProfile() {
    const updatedData = {
      id: this.data.userInfo.id,  // 把ID放进去
      nickname: this.data.userInfo.nickname,
      city: this.data.userInfo.city,
      province: this.data.userInfo.province,
      phone: this.data.userInfo.phone,
    };
  
    UserService.updateUser(updatedData).then(res => {
      if (res.code === 200) {
        wx.setStorageSync('userInfo', res.data);
        wx.showToast({ title: '修改成功' });
        wx.navigateBack({
          delta: 1  // 返回上一级页面
        });
      } else {
        wx.showToast({ title: '修改失败', icon: 'none' });
      }
    }).catch(() => {
      wx.showToast({ title: '网络错误', icon: 'none' });
    });
  }
  
});
